<template>
  <ul class="list">
    <li class="item"
      v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >
    {{item}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    // 定义一个数组，数组内储存A,B,C...
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    // 定义一个标识位，辨别手指是否触摸
    return {
      touchStatus: false,
      startY: 0
      // timer: null
    }
  },
  // 优化代码
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      // 兄弟组件传值，alphabet组件向list组件传值，通过兄弟alphabet->父组件city->兄弟list
      // 点击字母触发事件，并携带e.target.innerText
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        // if (this.timer) {
        //   clearTimeout(this.timer)
        // }
        // this.timer = setTimeout(() => {
        //   this.timer = null
        const touchY = e.touches[0].clientY - 79 // 减去蓝色上边框整体高度，得到手指触摸整体高度
        const index = Math.floor((touchY - this.startY)) / 20 // 取整（手指触摸高度 - 初始高度）/ 单个字母高度
        if (index >= 0 && index <= this.letters.length) {
          this.$emit('change', this.letters[index])
        }
        // }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    //字母垂直居中排列
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgcolor
</style>
